package es.pawer.android.listacompras;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import es.pawer.android.listacompras.biz.Item;
import es.pawer.android.listacompras.biz.ShoppingList;
import es.pawer.android.listacompras.biz.ShoppingListFacade;
import es.pawer.android.listacompras.data.DataException;
import es.pawer.android.listacompras.data.MyDatabaseHelper;

public class ShoppingListActivity extends ListActivity implements OnItemClickListener {
	
	ShoppingList shoppingList;
	int points=0;
	ShoppingListFacade facade;
	
	public ShoppingListActivity() {
		super();
		facade= new ShoppingListFacade();
		
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		MyDatabaseHelper.createInstance(getApplicationContext());
		List<ShoppingList> existingLists= facade.getAllLists();
		if (existingLists==null || existingLists.isEmpty()) {
			this.getMockList();
		} else {
			shoppingList = facade.getAllLists().get(0);
		}
		shoppingList=facade.populateList(shoppingList);
		this.setListAdapter(new ArrayItemAdapter(this,shoppingList.getItemList()));
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(this);
	}

	
	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
		// When clicked, show a toast with the TextView text
		view.setVisibility(View.GONE);
		shoppingList.getItemList().get(position).addOrderPoints(points);
		shoppingList.getItemList().get(position).setSelected(true);
		points++;
		if (shoppingList.isEveryItemSelected()) {
			this.updateList();
		}
	}


	private void updateList() {
		if (this.shoppingList.getItemList()!=null) {
			try {
				facade.updateList(this.shoppingList);
			} catch (DataException e) {
				Log.e("UI", "Error while updating the list", e);
				
			}
		}
	}
	
	private void getMockList() {
		ArrayList<Item> list= new ArrayList<Item>();
		this.shoppingList=new ShoppingList("Prueba");
		for (int i=0;i<15;i++) {
			Item it= new Item("AAA "+i);
			it.setUnits(i);
			list.add(it);
		}
		this.shoppingList.setItemList(list);
		saveList();
	}
	
	private void saveList() {
		if (this.shoppingList.getItemList()!=null) {
			try {
				facade.saveList(this.shoppingList);
			} catch (DataException e) {
				Log.e("UI", "Error while saving the list", e);
				
			}
		}
	}

}